//
//  DownloadViewController.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-10.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//
//  下载管理视图

#import "DownloadViewController.h"
#import "CourseModel.h"
#import "CourseVideoModel.h"
#import "CourseCell.h"
#import "DownloadCell.h"
#import "DownloadedCell.h"
#import "UIImageView+WebCache.h"
#import "DownloaderHelper.h"
#import "LoadCourseDataManager.h"
#import "PlayerVideoViewController.h"
#import "DetailViewController.h"

@interface DownloadViewController ()

@end

@implementation DownloadViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"下载";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downLoadedStartClicked:) name:kDownloadNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playLocalButtonClicked:) name:kPlayLocalBUttonNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadPauseButtonClicked:) name:kDownloadPauseNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self _initBarButtonItem];
    [self.tableView registerNib:[UINib nibWithNibName:@"CourseCell" bundle:nil] forCellReuseIdentifier:@"CourseCell"];
//    [self.tableView registerNib:[UINib nibWithNibName:@"DownloadCell" bundle:nil] forCellReuseIdentifier:@"DownloadCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DownloadedCell" bundle:nil] forCellReuseIdentifier:@"DownloadedCell"];
    DownloaderHelper *downloaderHelper = [DownloaderHelper shareInstance];
    downloaderHelper.delegate = self;
}

- (void)_initBarButtonItem
{
    //编辑按钮
    _editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_editButton setBackgroundImage:[UIImage imageNamed:@"btn_right.png"] forState:UIControlStateNormal];
    
    [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
    
    _editButton.titleLabel.font = [UIFont systemFontOfSize:11];
    [_editButton addTarget:self action:@selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    _editButton.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:_editButton];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 144, 30)];
    view.backgroundColor = [UIColor clearColor];
    //已下载
    _downLoadedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_downLoadedButton setBackgroundImage:[UIImage imageNamed:@"download_tab_loaded.png"] forState:UIControlStateNormal];
    [_downLoadedButton setTitle:@"已下载" forState:UIControlStateNormal];
    _downLoadedButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [_downLoadedButton addTarget:self action:@selector(downLoadedButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _downLoadedButton.frame = CGRectMake(77, 0, 77, 30);
    [view addSubview:_downLoadedButton];
    
    //下载中
    _downLoadingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_downLoadingButton setBackgroundImage:[UIImage imageNamed:@"download_tab_loading_active.png"] forState:UIControlStateNormal];
    [_downLoadingButton setTitle:@"下载中" forState:UIControlStateNormal];
    _downLoadingButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [_downLoadingButton addTarget:self action:@selector(downLoadingButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _downLoadingButton.frame = CGRectMake(0, 0, 77, 30);
    [view addSubview:_downLoadingButton];
    self.navigationItem.titleView = view;
}

- (void)downLoadingButtonClicked
{
    [_downLoadedButton setBackgroundImage:[UIImage imageNamed:@"download_tab_loaded.png"] forState:UIControlStateNormal];
    [_downLoadingButton setBackgroundImage:[UIImage imageNamed:@"download_tab_loading_active.png"] forState:UIControlStateNormal];
    _isDownLoadedShow = NO;
    [self backViewWhichShouldHideen];
    [self getDownloadModelData];

}

- (void)downLoadedButtonClicked
{
    [_downLoadedButton setBackgroundImage:[UIImage imageNamed:@"download_tab_loaded_active.png"] forState:UIControlStateNormal];
    [_downLoadingButton setBackgroundImage:[UIImage imageNamed:@"download_tab_loading.png"] forState:UIControlStateNormal];
    _isDownLoadedShow = YES;
    [self backViewWhichShouldHideen];
    [self getDownloadModelData];
    
}

- (void)editButtonClicked:(UIButton *)button;
{
    BOOL flag = !self.tableView.editing;
    if (flag)
    {
        [button setTitle:@"完成" forState:UIControlStateNormal];
    }
    else
    {
        [button setTitle:@"编辑" forState:UIControlStateNormal];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.tableView.editing = flag;
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --
#pragma 归档

- (void)getDownloadModelData
{
    //先读取本地文件
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    NSMutableArray *readModels = [NSMutableArray arrayWithArray:[dataManager loadDownloadData]];
    
    if (_showsArray != nil)
    {
        [_showsArray removeAllObjects];
        _showsArray = nil;
    }
    if (_downloadedShowsArray != nil)
    {
        [_downloadedShowsArray removeAllObjects];
        _downloadedShowsArray = nil;
    }
    
    _showsArray = [[NSMutableArray alloc] init];
    _downloadedShowsArray = [[NSMutableArray alloc] init];
    
    for (CourseModel *model in readModels)
    {
        BOOL flag = NO;
        for (CourseVideoModel *videoModel in model.videoList)
        {
            //被选择下载且不在下载中，且未被下载完
            if (videoModel.isSelectedToDownload  && !videoModel.isDownloaded)
            {
//                videoModel.isDownloading = YES;
                [model.downloadList addObject:videoModel];
                flag = YES;
            }
            
        }
        if (flag)
        {
            [_showsArray addObject:model];

        }
    
    }//for (CourseModel *model in readModels)
    //下载完的项目添加到
    for (CourseModel *model in readModels)
    {
        BOOL flag = NO;
        for (CourseVideoModel *videoModel in model.videoList)
        {
            if (videoModel.isDownloaded)
            {
                //下载完的项目添加数组中
                [model.downloadedList addObject:videoModel];
                flag = YES;
            }
        }
        if (flag)
        {
            [_downloadedShowsArray addObject:model];
        }
    }//for (CourseModel *model in readModels)
    [self backViewWhichShouldHideen];
    [self.tableView reloadData];
}

- (void)backViewWhichShouldHideen
{
    if (_isDownLoadedShow)
    {
        if (_downloadedShowsArray.count != 0)
        {
            self.noDownloadView.hidden = YES;
            self.noDownloadedView.hidden = YES;
            _editButton.enabled = YES;
        }
        else
        {
            self.noDownloadView.hidden = YES;
            self.noDownloadedView.hidden = NO;
            _editButton.enabled = NO;
            self.tableView.editing = NO;
            [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
        
        }
    }
    else
    {
        if (_showsArray.count != 0)
        {
            self.noDownloadView.hidden = YES;
            self.noDownloadedView.hidden = YES;
            _editButton.enabled = YES;
        }
        else
        {
            self.noDownloadView.hidden = NO;
            self.noDownloadedView.hidden = YES;
            _editButton.enabled = NO;
            self.tableView.editing = NO;
            [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isDownLoadedShow)
    {
        if (_downloadedShowsArray.count == 0)
        {
            return 0;
        }
        return _downloadedShowsArray.count;
    }
    else
    {
        return _showsArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isDownLoadedShow)
    {
        CourseModel *model = _downloadedShowsArray[section];
        return model.downloadedList.count+1;
    }
    else
    {
        CourseModel *model = _showsArray[section];
        return model.downloadList.count+1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isDownLoadedShow)
    {
        CourseModel *model = [_downloadedShowsArray objectAtIndex:indexPath.section];
        if (indexPath.row == 0)
        {
            CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CourseCell"];
            
            
            cell.titleLabel.text = model.title;
            cell.classLabel.text = model.tags;
            cell.playCountLabel.text = [NSString stringWithFormat:@"%@", model.playcount];
            cell.updatePlayCountLabel.text = [NSString stringWithFormat:@"%@", model.updatedPlaycount];
            [cell.courseImageView setImageWithURL:[NSURL URLWithString:model.imagePath]];
            
            return cell;
        }
        else
        {
            DownloadedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownloadedCell"];
            CourseVideoModel *videoModel = model.downloadedList[indexPath.row-1];
            cell.playLocalButton.tag = [[NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber] integerValue] + DownloadedCellButtonTag;
            cell.pnumberLabel.text = [NSString stringWithFormat:@"第%@课", videoModel.pnumber];
            cell.titleLabel.text = videoModel.title;
            cell.capacityLabel.text = [NSString stringWithFormat:@"%0.2fM", [videoModel.mp4size doubleValue]/1024.0/1024.0];
            return cell;
        }
    }
    else
    {
        CourseModel *model = [_showsArray objectAtIndex:indexPath.section];
        if (indexPath.row == 0)
        {
            CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CourseCell"];
            
            
            cell.titleLabel.text = model.title;
            cell.classLabel.text = model.tags;
            cell.playCountLabel.text = [NSString stringWithFormat:@"%@", model.playcount];
            cell.updatePlayCountLabel.text = [NSString stringWithFormat:@"%@", model.updatedPlaycount];
            [cell.courseImageView setImageWithURL:[NSURL URLWithString:model.imagePath]];
            
            return cell;
        }
        else
        {
//            DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownloadCell"];
            
            DownloadCell *cell = [[NSBundle mainBundle] loadNibNamed:@"DownloadCell" owner:self options:nil][0];
            CourseVideoModel *videoModel = model.downloadList[indexPath.row-1];
            cell.tag = [[NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber] integerValue] + DownloadCellTag;
            cell.downloadPauseButton.tag = [[NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber] integerValue] + DownloadCellPauseButtonTag;
            if (videoModel.isDownloadPause)
            {
                [cell.downloadPauseButton setImage:[UIImage imageNamed:@"downloadcell_start.png"] forState:UIControlStateNormal];
            }
            cell.pnumberLabel.text = [NSString stringWithFormat:@"第%@课", videoModel.pnumber];
            cell.titleLabel.text = videoModel.title;
            cell.downloadProgressView.progressImage = [UIImage imageNamed:@"download_progressbar.png"];
            cell.downloadProgressView.frame = CGRectMake(cell.downloadProgressView.frame.origin.x, cell.downloadProgressView.frame.origin.y, cell.downloadProgressView.frame.size.width, 13);
            cell.downloadProgressView.progress = videoModel.downloadProgress;
            cell.downloadProgressView.tag = [[NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber] integerValue] + DownloadCellProgressTag;
            cell.downloadProgressLabel.text = [NSString stringWithFormat:@"%0.0fM", videoModel.downloadProgress*[videoModel.mp4size doubleValue]/1024.0/1024.0];
            cell.downloadTotleLabel.text = [NSString stringWithFormat:@"%0.0fM", [videoModel.mp4size doubleValue]/1024.0/1024.0];
            
            return cell;
        }
    }
 
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return 92;
    }
    return 54;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isDownLoadedShow)
    {
        CourseModel *model = _downloadedShowsArray[indexPath.section];
        CourseVideoModel *videoModel = model.downloadedList[indexPath.row-1];
        for (CourseVideoModel *tempVideo in model.videoList)
        {
            if ([videoModel.pnumber isEqualToNumber:tempVideo.pnumber])
            {
                NSFileManager *fileManager = [NSFileManager defaultManager];
                BOOL isExists = [fileManager fileExistsAtPath:videoModel.localPlayPath];
                if (isExists)
                {
                    [fileManager removeItemAtPath:videoModel.localPlayPath error:nil];
                    tempVideo.isSelectedToDownload = NO;
                    tempVideo.isDownloading = NO;
                    tempVideo.isDownloaded = NO;
                }
                
            }
        }
        
        LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
        [dataManager writeToDownloadArchiverWithModel:model];
        [self getDownloadModelData];
    }
    else
    {
        CourseModel *model = _showsArray[indexPath.section];
        CourseVideoModel *videoModel = model.downloadList [indexPath.row-1];
        for (CourseVideoModel *tempVideo in model.videoList)
        {
            if ([videoModel.pnumber isEqualToNumber:tempVideo.pnumber])
            {
                tempVideo.isSelectedToDownload = NO;
                tempVideo.isDownloading = NO;
            }
        }
        
        if (model.downloadList.count == 0)
        {
            _editButton.enabled = NO;
            self.tableView.editing = NO;
            [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
        }
        LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
        [dataManager writeToDownloadArchiverWithModel:model];
        [self getDownloadModelData];
    }
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return NO;
    }
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isDownLoadedShow)
    {
        if (indexPath.row == 0)
        {
            DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
            
            CourseModel *model = [_downloadedShowsArray objectAtIndex:indexPath.section];
            detailController.videoCode = model.plid;
            
            //隐藏tabbarView;
            UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
            view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
            
            [self.navigationController pushViewController:detailController animated:YES];
        }
    }
    else
    {
        if (indexPath.row == 0)
        {
            DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
            
            CourseModel *model = [_showsArray objectAtIndex:indexPath.section];
            detailController.videoCode = model.plid;
            
            //隐藏tabbarView;
            UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
            view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
            
            [self.navigationController pushViewController:detailController animated:YES];
        }
    }
}

#pragma mark -- 
#pragma mark NSNotification
- (void)downLoadedStartClicked:(NSNotification *)note
{
//    CourseModel *model = 
    [self getDownloadModelData];
}

- (void)playLocalButtonClicked:(NSNotification *)note
{
    UIButton *button = (UIButton *)note.object;
    NSString *str = nil;
    for (CourseModel *model in _downloadedShowsArray)
    {
        for (CourseVideoModel *videoModel in model.downloadedList)
        {
            NSInteger videoTag = [[NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber] integerValue] + DownloadedCellButtonTag;
            if (videoTag == button.tag)
            {
                str = videoModel.localPlayPath;
                [self presentVideoByCourseModel:videoModel andModel:model];
            }
        }
    }
    
}

- (void)presentVideoByCourseModel:(CourseVideoModel *)videoModel andModel:(CourseModel *)model
{
    PlayerVideoViewController *player = [[PlayerVideoViewController alloc] initWithNibName:@"PlayerVideoViewController" bundle:nil withPlayType:PlayWithLocal];
    player.courseModel = model;
    player.videoModel = videoModel;
    [self presentViewController:player animated:YES completion:nil];
}

- (void)downloadPauseButtonClicked:(NSNotification *)note
{
    DownloaderHelper *downloadHelper = [DownloaderHelper shareInstance];
    UIButton *button = note.object;
    CourseModel *model = [[CourseModel alloc] init];
    CourseVideoModel *videoModel = [[CourseVideoModel alloc] init];
    NSString *str = nil;
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    //    CourseVideoModel *tempVideoModel = nil;
    NSMutableArray *readModels = [NSMutableArray arrayWithArray:[dataManager loadDownloadData]];
    for (CourseModel *tempModel in readModels)
    {
        for (CourseVideoModel *tempVideoModel in tempModel.videoList)
        {
            NSInteger videoTag = [[NSString stringWithFormat:@"%d%@", tempModel.indentify, tempVideoModel.pnumber] integerValue] + DownloadCellPauseButtonTag;

            if (videoTag == button.tag)
            {
                model = tempModel;
                videoModel = tempVideoModel;
                str = [NSString stringWithFormat:@"%d%@", tempModel.indentify, tempVideoModel.pnumber];
            }
        }
    }

    if (videoModel.isDownloadPause)
    {
        videoModel.isDownloadPause = NO;
        [downloadHelper startDownload:videoModel.repovideourlmp4 withKey:str];
        [button setImage:[UIImage imageNamed:@"downloadcell_pause.png"] forState:UIControlStateNormal];
        
    }
    else
    {
        videoModel.isDownloadPause = YES;
        [downloadHelper pauseDownload:str];
        [button setImage:[UIImage imageNamed:@"downloadcell_start.png"] forState:UIControlStateNormal];
    }
    [dataManager writeToDownloadArchiverWithModel:model];
}

#pragma mark DownloaderHelper Delegate
- (void)fileContentLength:(long long)byts key:(NSString *)fileKey
{
    
    //    NSLog(@"FUNCTION:%s--LINE:%d--byts:%lld--key:%@",__FUNCTION__,__LINE__,byts,fileKey);LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    //    CourseVideoModel *tempVideoModel = nil;
//     LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
//    NSMutableArray *readModels = [NSMutableArray arrayWithArray:[dataManager loadDownloadData]];
//    for (CourseModel *model in readModels)
//    {
//        for (CourseVideoModel *videoModel in model.videoList)
//        {
//            NSString *str = [NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber];
//            if ([str isEqualToString:fileKey])
//            {
//                DownloadCell *cell = (DownloadCell *)[self.view viewWithTag:[fileKey integerValue]+DownloadCellTag];
//                
//                
//            }
//        }
//    }
//    
//    [dataManager writeToDownloadArchiverWithArray:readModels];
//    DownloadCell *cell = (DownloadCell *)[self.view viewWithTag:[fileKey integerValue] + DownloadCellTag];
//    cell.downloadTotleLabel.text = [NSString stringWithFormat:@"%0.3lldM", byts/1024/1024];
    
}

- (void)setProgress:(float)newProgress filePath:(NSString *)filePath key:(NSString *)fileKey
{
//    NSLog(@"FUNCTION:%s--LINE:%d--key:%@--newProgress:%.2f ",__FUNCTION__,__LINE__,fileKey,newProgress);

    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    NSMutableArray *readModels = [NSMutableArray arrayWithArray:[dataManager loadDownloadData]];
    for (CourseModel *model in readModels)
    {
        for (CourseVideoModel *videoModel in model.videoList)
        {
            NSString *str = [NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber];
            if ([str isEqualToString:fileKey])
            {
                DownloadCell *cell = (DownloadCell *)[self.view viewWithTag:[fileKey integerValue]+DownloadCellTag];
                videoModel.downloadProgress = newProgress;
                cell.downloadProgressView.progress = newProgress;
                cell.downloadProgressLabel.text = [NSString stringWithFormat:@"%0.0fM", newProgress*[videoModel.mp4size doubleValue]/1024.0/1024.0];
            }
        }
    }
    
    [dataManager writeToDownloadArchiverWithArray:readModels];


    
}


- (void)requestFinished:(NSString *)filePath key:(NSString *)fileKey
{
//    NSLog(@"FUNCTION:%s--LINE:%d--key:%@ ",__FUNCTION__,__LINE__,fileKey);
//    
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    NSMutableArray *readModels = [NSMutableArray arrayWithArray:[dataManager loadDownloadData]];
    //找出下载完的视频位置
    for (CourseModel *model in readModels)
    {
        for (CourseVideoModel *videoModel in model.videoList)
        {
            NSString *str = [NSString stringWithFormat:@"%d%@", model.indentify, videoModel.pnumber];
            if ([str isEqualToString:fileKey])
            {
                videoModel.isDownloaded = YES;
                videoModel.localPlayPath = filePath;
            }
        }
    }
    
    [dataManager writeToDownloadArchiverWithArray:readModels];
    
    [self getDownloadModelData];
    
}

- (void)requestFailed:(NSString *)fileKey
{
//    NSLog(@"FUNCTION:%s--LINE:%d--key:%@ ",__FUNCTION__,__LINE__,fileKey);
    UIAlertView * alert= [[UIAlertView alloc] initWithTitle:nil message:@"网络不稳定,资源下载失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消",nil];
    [alert show];
    
}


#pragma mark --
#pragma mark viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    [UIView animateWithDuration:0.35 animations:^{
        view.frame = CGRectMake(0, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    }];
    [self getDownloadModelData];
}



@end
